#include "windowCaptureRoboComp.h"

windowCaptureRoboComp::windowCaptureRoboComp(QWidget* widgetConstr, CameraPrx camPrxConstr, DifferentialRobotPrx basePrxConstr)
	: camPrx(camPrxConstr), basePrx(basePrxConstr), QDialog(widgetConstr, Qt::Dialog) {
	setupUi(this);
	myTimer = new QTimer();

	connect(myPushButtonCapture, SIGNAL(clicked(bool)), this, SLOT(capture()));
	connect(myPushButtonOK, SIGNAL(clicked(bool)), this, SLOT(ok()));
	connect(myPushButtonCancel, SIGNAL(clicked(bool)), this, SLOT(close()));
	connect(myTimer, SIGNAL(timeout()), this, SLOT(compute()));

	try {
		camParams = camPrx->getCamParams();
		qDebug() << "WxH:"<< camParams.width <<"x"<< camParams.height;
		imgSize = camParams.size*3;	//Tamaño de la imagen(ancho*alto*3 (cada plano RGB))	
		imageRealTime = new QImage(camParams.width, camParams.height, QImage::Format_RGB888);
		myTimer->start(1000/(int)camParams.FPS);
	}
	catch(const Ice::Exception& ex) {
		myLabelRealTime->setText("There is some problem with the cam.\nCannot get images.");
		myLabelCaptured->setText("Damn!");
		myPushButtonOK->setEnabled(false);
		myPushButtonCapture->setEnabled(false);
		qWarning("No CameraComp alive. Continue...");
		std::cout << ex;
	}
	show();
}




void windowCaptureRoboComp::capture() {
	myLabelCaptured->setPixmap(QPixmap::fromImage(*imageRealTime));
}




void windowCaptureRoboComp::ok() {
	Worker* myWorker = qobject_cast<Worker*>(myWidget);
	windowImage* myWindowImage;
	if (!myLabelCaptured->pixmap()==0) myWindowImage = new windowImage(new QImage(myLabelCaptured->pixmap()->toImage()), tr("WebCam Captured Image %1").arg(++myWorker->capturedWebcamImages), windowImage::capturedWebcam);
	else myWindowImage = new windowImage(new QImage(myLabelRealTime->pixmap()->toImage()), tr("WebCam Captured Image %1").arg(++myWorker->capturedWebcamImages), windowImage::capturedWebcam);
	myWorker->myMdiArea->addSubWindow(myWindowImage);
	close();
	myWindowImage->show();
}




void windowCaptureRoboComp::close() {
	myTimer->stop();
	QWidget::close();
}




void windowCaptureRoboComp::compute() {
	try {
		camPrx->getRGBPackedImage(0, camImagesRaw, headState, baseState); // See Camera.ice
		memcpy(imageRealTime->bits(), &camImagesRaw[0], imgSize);
		myLabelRealTime->setPixmap(QPixmap::fromImage(*imageRealTime));
	}
	catch(const Ice::Exception& ex) {
		qWarning("Camera: get image failure.");
		std::cout << ex;
	}
}